﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography.X509Certificates;

namespace Streaming_Service.SQL_Ting {
    public class DBFunc {
        private static readonly Random Rnd = new Random();

        private static readonly char[] RandChars =
            ("abcdefghijklmnopqrstuvwxyz" +
            "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
            "0123456789"
            ).ToCharArray();

        private static readonly char[] RandCharsXtd = RandChars.Concat(
            "!\"#¤%&/()=?`´§½@£$€{[]}|€µ<>\\,;.:-_*'^¨~ ".ToCharArray()
            ).ToArray();

        public static int UnixTimestamp() {
            return (int)(DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds;
        }

        public static int Rand(int min, int max) {
            if (min > max) return Rand(max, min);
            return Rnd.Next(min, max + 1);
        }

        public static string RandStr(uint len) {
            return RandStr(len, RandChars);
        }

        public static string RandStrXtd(uint len) {
            return RandStr(len, RandCharsXtd);
        }

        public static string RandStr(uint len, char[] chars) {
            if(len < 1) return string.Empty;
            var sb = new StringBuilder();
            for(var i = 0; i < len; i++) {
                sb.Append(chars[Rand(0, chars.Length - 1)]);
            }
            return sb.ToString();
        }

        public static string MD5(string toHash) {
            if (toHash == null) return "";
            return MD5(Encoding.Default.GetBytes(toHash));
        }

        public static string MD5(byte[] toHash) {
            if (toHash == null) return "";
            var hbytes = System.Security.Cryptography.MD5.Create().ComputeHash(toHash);
            var sb = new StringBuilder();
            foreach(var hb in hbytes) {
                sb.Append(hb.ToString("x2"));
            }
            return sb.ToString();
        }

        public static int ParseInt(string text) {
            return ParseInt(text, 0);
        }

        public static int ParseInt(string text, int defaultValue) {
            var parsedValue = defaultValue;
            return int.TryParse(text, out parsedValue) ? parsedValue : defaultValue;
        }

        public static DateTime ParseDateTime(string text) {
            return ParseDateTime(text, DateTime.MinValue);
        }

        public static DateTime ParseDateTime(string text, DateTime defaultValue) {
            var parsedValue = defaultValue;
            return DateTime.TryParse(text, out parsedValue) ? parsedValue : defaultValue;
        }
    }
}